package com.cw.jeeyt.provider;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.cw.jeeyt.common.utils.CaptchaMaker;
import com.cw.jeeyt.service.bo.security.SecurityUserBo;
import com.cw.jeeyt.service.intf.security.SecurityUserService;

/**
 * 权限验证
 *
 * @author: chenw
 * @create: 2018-11-08 13:30
 */
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private SecurityUserService securityUserService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        ServletRequestAttributes requestAttributes
            = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();
        String verifyCode = request.getParameter("verifyCode");
        boolean verify = CaptchaMaker.validate(request, response, verifyCode);
        if (!verify) {
            throw new BadCredentialsException("验证码错误");
        }
        String account = authentication.getName();
        String password = (String) authentication.getCredentials();
        SecurityUserBo userInfoBo = securityUserService.checkUserLogin(account, password);
        Collection<? extends GrantedAuthority> authorities = userInfoBo.getAuthorities();
        // 构建返回的用户登录成功的token
        return new UsernamePasswordAuthenticationToken(userInfoBo, password, authorities);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
